package com.panda.pandawash.activity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.panda.pandawash.bean.BindDevicesBean;
import com.panda.pandawash.fragment.MonitorRunningInfoFragment;
import com.panda.pandawash.util.RoomlockGattAttributes;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.panda.pandawash.R;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.base.BaseActivity;
import com.panda.pandawash.fragment.MonitorInfoFragment;
import com.panda.pandawash.fragment.MonitorSettingFragment;
import com.panda.pandawash.fragment.MonitorStatusFragment;
import com.panda.pandawash.model.MotorDeviceInfoMessage;
import com.panda.pandawash.model.MotorSingleStatusMessage;
import com.panda.pandawash.service.BluetoothLeService;
import com.panda.pandawash.view.LoadingDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

public class MotorMonitorActivity extends BaseActivity {

    private static String TAG = "MotorMonitorActivity";

    public static final String EXTRAS_DEVICE_NAME = "device_name";
    public static final String EXTRAS_DEVICE_ADDRESS = "device_address";
    public static final String EXTRAS_DEVICE_MODEL = "device_model";

    private LoadingDialog mConnectDialog;

    private MonitorStatusFragment mMonitorStatusFragment = new MonitorStatusFragment();;

    private BluetoothLeService mBluetoothLeService;

    private boolean mConnected = false;
    private BluetoothGattCharacteristic mTxCharacteristic;
    private BluetoothGattCharacteristic mRxCharacteristic;

    private String mDeviceAddress;
    private String mDeviceName;
    private int mDeviceModel;

    private Boolean mydebug = false;
    private Boolean motor_isruning = false;

    private Boolean motor_infoBoolean = true;
    private Boolean motor_is_waitinginfo = false;
    private Boolean motor_is_waitingstatus = false;

    /**
     * startup code A0 00 17 C0 77
     * shutup code A0 00 37 C0 57
     * baseinfo code A0 00 0F C0 6F
     * statusinfo code A0 00 36 C0 56
     */



    /**
     * baseinfo
     * 80 51 0F 20 14 01 82 00 00 A4 01 FF 00 0C 05 04
     * 10 0C 04 00 00 00 00 00 23 00 00 00 00 00 00 00
     * D0 01 FA 00 19 00 43 00 00 00 00 00 00 00 00 00
     * 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 00
     * 00 32 1E 00 00 00 00 00 00 00 01 D4 00 00 00 00 C0
     */

    /**
     * statusinfo
     * 80 16 36 00 00 00 00 13
     * 02 00 00 00 00 00 00 00
     * 00 00 00 00 00 C0
     */

    private final byte[] CMD_STARTUP = { (byte) 0xa0, 0x00, 0x17, (byte) 0xc0, 0x77 };
    private final byte[] CMD_SHUTDOWN = { (byte) 0xa0, 0x00, 0x37, (byte) 0xc0, 0x57 };
    private final byte[] CMD_BASE_INFO = { (byte) 0xa0, 0x00, 0x0F, (byte) 0xc0, 0x6F };
    private final byte[] CMD_STATUS = { (byte) 0xa0, 0x00, 0x36, (byte) 0xc0, 0x56 };

    private LoadingDialog startupdialog;
    private LoadingDialog shutdowndialog;
    private int tanvalue = 420;
    private float Lrefcurrent = (float) 13.0;
    private int empty_load = 812;
    private int full_load = 498;

    private MyListener myListener;

    private Toolbar toolbar;

    private Handler mHandler = new Handler();
    private int count_times = 0;
    private long sendCmdTime = 0;

    private byte[] settingdata;

    public interface MyListener {
        void updateDeviceName(String device_name);
    }

    public void setMyListener(MyListener myListener) {

        this.myListener = myListener;
    }

    private static MotorMonitorActivity  mMonitorActivity ;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startupdialog = new LoadingDialog(this, "开启洗车机 ...");
        shutdowndialog = new LoadingDialog(this, "关闭洗车机 ...");

        ///获取数据
        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
        mDeviceModel = intent.getIntExtra(EXTRAS_DEVICE_MODEL, 1);
        Log.e(TAG, "mDeviceName  = "+ mDeviceName);
        setContentView(R.layout.activity_motor_monitor);
        initToolbar();
        addFragment(R.id.fl_container, mMonitorStatusFragment,"monitorstatus");
        initResources();
        mMonitorActivity = this;

    }

    public static MotorMonitorActivity  getInstance(){

        return mMonitorActivity ;

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.monitor_info_menu, menu);//加载menu文件到布局
        return true;
    }


    private void initToolbar(){
        Log.d("hys123","initToolbar");
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.showOverflowMenu();
        if(mDeviceName != null) {
            toolbar.setTitle(mDeviceName);
        }else{
            toolbar.setTitle("Motor monitor");
        }
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                if (item.getItemId() == R.id.device_info) {
                    Log.d("hys123","go into infosetting");
                    Intent intentPro = new Intent(MotorMonitorActivity.this, ProductInfoActivity.class);
                    intentPro.putExtra(MonitorInfoFragment.MOTOR_STATUS_INFO,
                            parseMonitorInfo());
                    intentPro.putExtra(EXTRAS_DEVICE_MODEL, mDeviceModel);
                    startActivity(intentPro);


                } else if (item.getItemId() == R.id.device_setting) {
                    Log.d("hys123","into device setting");
                    Intent intentPara = new Intent(MotorMonitorActivity.this, ParameterSetActivity.class);
                    intentPara.putExtra(MonitorSettingFragment.COMMAND_ECHO, settingdata);
                    intentPara.putExtra(MonitorSettingFragment.DEVICE_NAME, mDeviceName);
                    intentPara.putExtra(MonitorSettingFragment.MONITOR_SETTING_INFO, parseMonitorSetting());
                    startActivity(intentPara);

                } else if (item.getItemId() == R.id.device_status) {
                    Log.d("hys123","go into device status");
                    Intent intentStatus = new Intent(MotorMonitorActivity.this, ProductStatusActivity.class);
                    intentStatus.putExtra(MonitorRunningInfoFragment.MOTOR_STATUS_INFO,
                            parseStatusInfo());
                    startActivity(intentStatus);


                }
                return true;
            }
        });

    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);

        return intentFilter;
    }


    private String parseMonitorInfo(){

        Log.d("hys123","into parseMonitorInfo ");
        JSONObject mJsonObject = new JSONObject();

        try {
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_PRODUCTOR_NAME,
                    infoMessage.getMotorProductorCode());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_PRODUCT_DATE,
                    infoMessage.getproductDateString());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_CHECK_REAL,
                    infoMessage.isMotorReal());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_VERSION,
                    infoMessage.getMotorVersion());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_SERIAL_ID,
                    infoMessage.getMotorSerialId());
            Log.i(TAG, "cmd:" + mJsonObject.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return mJsonObject.toString();

    }

    private String parseMonitorSetting(){

        JSONObject mJsonObject = new JSONObject();

        try {
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_SHUTGUN_DELAY_VALUE,
                    String.valueOf(infoMessage.getsgDelay()));
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_STARTGUN_DELAY_VALUE,
                    String.valueOf(infoMessage.getogDelay()));
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_MAX_CONTINUE_RUN_VALUE,
                    String.valueOf(infoMessage.getMaxContinueRuningTime()));
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_SJ_DELAY_VALUE,
                    String.valueOf(infoMessage.getsjdelayTime()));
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_STARTUP_METHOD_VALUE,
                    infoMessage.getstartUpMethod());
            infoMessage.setDeviceStatus(infoMessage.getstartUpMethod());
            Log.i(TAG, "cmd:" + mJsonObject.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return mJsonObject.toString();

    }

    private void initResources(){
        Intent gattServiceIntent = new Intent(MotorMonitorActivity.this, BluetoothLeService.class);
        	/*dialog.setCancelable(false);
		dialog弹出后会点击屏幕或物理返回键，dialog不消失*/
        //dialog.setCanceledOnTouchOutside(false);	//dialog弹出后会点击屏幕，dialog不消失；点击物理返回键dialog消失
        startupdialog.setCanceledOnTouchOutside(false);
        shutdowndialog.setCanceledOnTouchOutside(false);
        //mConnectDialog.show();
        showConnectingDialog();	//显示进度圈

        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        //registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        motor_isruning = false;

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        unregisterReceiver(mGattUpdateReceiver);
        if (mBluetoothLeService != null) {
            mBluetoothLeService.disconnect();
        }
        unbindService(mServiceConnection);
    }


    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                Log.i(TAG, "ACTION_GATT_CONNECTED");
  //              mConnected = true;
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED
                    .equals(action)) {
                Log.i(TAG, "ACTION_GATT_DISCONNECTED");
                mConnected = false;
                motor_isruning = false;
                mHandler.removeCallbacks(mRunnable);
                invalidateOptionsMenu();
                showConnectingDialog();
                if (mBluetoothLeService != null) {
                    mBluetoothLeService.connect(mDeviceAddress);
                }
                //Toast.makeText(MotorMonitorActivity.this,"ble connect fail",Toast.LENGTH_SHORT).show();
                //finish();

            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED
                    .equals(action)) {
                Log.i(TAG, "ACTION_GATT_SERVICES_DISCOVERED");
                if (mBluetoothLeService != null)
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                String data = intent.getStringExtra(BluetoothLeService.EXTRA_DATA_HEX);
                if (data == null) {
                    //Toast.makeText(MotorMonitorActivity.this,"ble data fail",Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.d("hys123","MotorMonitorActivity BluetoothLeService.ACTION_DATA_AVAILABLE data" + intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA));
                handle_msg_data(intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA));

            }
        }

    };

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub

            if (motor_isruning&& SystemClock.elapsedRealtime() - sendCmdTime > 2000) {

                Log.i(TAG, "Main thread with data");
                if (motor_infoBoolean && count_times == 0) {
                    Log.i(TAG, "Get motor info");
                    motor_is_waitinginfo = true;
                    RobotInfo();
                } else {
                    // mHandler.postDelayed(mRunnable, 1000);
                    Log.i(TAG, "Get motor status");
                    motor_infoBoolean = true;
                    motor_is_waitingstatus = true;
                    RobotStatus();
                }

                mHandler.postDelayed(mRunnable, 1000);
                count_times++;
                count_times = count_times % 60;
            } else {
                //Log.i(TAG, "Main thread idle");
                mHandler.postDelayed(mRunnable, 100);
            }

            Log.i(TAG, "Main thread counts = " + count_times);
        }
    };


    public void send_msg_to_motor(final byte[] cmd) {

        int wait_time = 10;

        //motor_isruning = false;
        sendCmdTime = SystemClock.elapsedRealtime();
        if (motor_is_waitingstatus == true){
            wait_time = 200;
        }else if (motor_is_waitinginfo == true){
            wait_time = 500;
        }else {
            wait_time = 10;
        }

        Log.i(TAG, "stop device_scan thread, wait time: " + wait_time);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Log.i(TAG, "sub thread");
                sendMsgtoRoomLock(mTxCharacteristic, cmd);
            }
        }, wait_time);
    }

    public void send_msg_to_updateToolar(final String devicename) {
        toolbar.setTitle(devicename);


    }

    public void send_msg_to_motor_and_update_info(final byte[] cmd) {
        Log.d("hys123","MotorMonitorActivity send_msg_to_motor_and_update_info cmd " + cmd);

        int wait_time = 10;

        if (motor_is_waitingstatus == true){
            wait_time = 200;
        }else if (motor_is_waitinginfo == true){
            wait_time = 500;
        }else {
            wait_time = 10;
        }

        Log.i(TAG, "stop device_scan thread, wait time: " + wait_time);
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Log.i(TAG, "sub thread");
                sendMsgtoRoomLock(mTxCharacteristic, cmd);
                //mStatusHandler.postDelayed(mStatusRunnable, 300);
            }
        }, wait_time);

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Log.i(TAG, "sub thread");
                sendMsgtoRoomLock(mTxCharacteristic, CMD_BASE_INFO);
                //mStatusHandler.postDelayed(mStatusRunnable, 300);
            }
        }, wait_time + 10);
    }

    Boolean sendMsgtoRoomLock(final BluetoothGattCharacteristic characteristic,
                              final byte[] msg) {
        new Thread() {

            @SuppressLint("NewApi")
            public void run() {
                while (!mBluetoothLeService.canWriteCharacteristic()) {
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                    }
                }
                int i = 0;
                while (i < 1) {
                    int charaProp = characteristic.getProperties();
                    if ((charaProp | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                        int j = 0;
                        for (j = 0; j < msg.length / 20; j++) {
                            byte[] data = new byte[20];

                            System.arraycopy(msg, j * 20, data, 0, 20);
                            if (mydebug)
                                Log.i(TAG, new String(data));

                            characteristic.setValue(data);
                            mBluetoothLeService
                                    .writeCharacteristic(characteristic);
                            try {
                                Thread.sleep(200);
                                i++;
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        if (j * 20 < msg.length) {
                            byte[] data = new byte[msg.length - j * 20];
                            System.arraycopy(msg, j * 20, data, 0, msg.length
                                    - j * 20);

                            if (mydebug)
                                Log.i(TAG, new String(data));
                            characteristic.setValue(data);
                            mBluetoothLeService
                                    .writeCharacteristic(characteristic);
                            i++;
                            break;
                        }
                    }
                }
            }
        }.start();
        return true;

    }

    @SuppressLint("NewApi")
    /*显示所有支持的服务和特性*/
    private boolean displayGattServices(List<BluetoothGattService> gattServices) {
        boolean isRoomLock = false;
        boolean hasRoomlockService = false;

        for (BluetoothGattService gattService : gattServices) {//取出每一个gattService
            String uuid = gattService.getUuid().toString();//获取UUID
            /*UUID是正确的*/
            if (RoomlockGattAttributes.isUUIDEqualwithRoomLockService(uuid)) {
                List<BluetoothGattCharacteristic> gattCharacteristics = gattService
                        .getCharacteristics();//获取特征

                hasRoomlockService = true;
                Log.d(TAG, "room lock service");
                for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {

                    uuid = gattCharacteristic.getUuid().toString();
                    Log.d(TAG, uuid);

                    if (RoomlockGattAttributes.isUUIDEqualwithTxChannel(uuid)) {
                        mTxCharacteristic = gattCharacteristic;
                        Log.i(TAG, "Tx channel found;");
                        continue;
                    }

                    if (RoomlockGattAttributes.isUUIDEqualwithRxChannel(uuid)) {

                        mRxCharacteristic = gattCharacteristic;
                        mBluetoothLeService.setCharacteristicNotification(
                                mRxCharacteristic, true);
                        Log.i(TAG, "Rx channel found;");
                        continue;
                    }
                }

            }

        }

        /*连接成功*/
        if (hasRoomlockService && mTxCharacteristic != null
                && mRxCharacteristic != null) {
            isRoomLock = true;
            motor_isruning = true;
            showConnected("连接成功");
            addBindDevices(mDeviceModel, mDeviceName, mDeviceAddress, null);
            CDApplication.getIntance().setUserMAC(mDeviceAddress);
            //ParameterSetActivity.getInstance().mMonitorSettingFragment.updateDeviceName(mDeviceName);
            updateMotorRuning(false);
            mConnected = true;
            mHandler.postDelayed(mRunnable, 20);
            if (mConnectDialog != null) {
                mConnectDialog.cancel();	//进度圈停止转动
                mConnectDialog = null;
            }
            return isRoomLock;
        }

        new Thread() {
            public void run() {
                try {
                    unregisterReceiver(mGattUpdateReceiver);
                    mBluetoothLeService.disconnect();
                    Thread.sleep(2000);
                    //mBluetoothLeService.discoverServices();	//停止搜索蓝牙设备
                    registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
                    mBluetoothLeService.connect(mDeviceAddress);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            };
        }.start();
        return isRoomLock;
    }

    private void showConnectingDialog() {
        if (mConnectDialog != null && !isFinishing()) {
            mConnectDialog.cancel();
        }

        mConnectDialog = new LoadingDialog(this, "正在连接中...");
        mConnectDialog.setCanceledOnTouchOutside(false);
        mConnectDialog.show();
    }

    public void showConnected(String string) {
        Toast toast = Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    private void addBindDevices(int model, String name, String mac_address,
                                String pet_name) {
        BindDevicesBean bindDevicesBean = new BindDevicesBean();
        bindDevicesBean.setModel(model);
        bindDevicesBean.setName(name);
        bindDevicesBean.setMacAddress(mac_address);
        bindDevicesBean.setPetName(pet_name);
        saveDeviceToSQ(bindDevicesBean, mac_address, model, name, pet_name);
    }

    private void updateMotorRuning(boolean runing) {
        Intent mIntent = new Intent();
        mIntent.putExtra(MonitorStatusFragment.MOTOR_RUNING, runing);
        mMonitorStatusFragment.onActivityResult(0, MonitorStatusFragment.CONNECTED_FLAG, mIntent);
    }

    private void saveDeviceToSQ(BindDevicesBean device, String mac_address,
                                int model, String name, String pet_name) {
        DbUtils dbUtils = CDApplication.getIntance().getDbUtil();

        try {

            BindDevicesBean deviceQuery = dbUtils.findFirst(Selector.from(
                    BindDevicesBean.class).where("mac_address", "=",
                    mac_address));
            if (deviceQuery == null) {
                dbUtils.save(device);
            } else if (deviceQuery.getModel() != model) {
                dbUtils.update(device,
                        WhereBuilder.b("mac_address", "=", mac_address),
                        "name", "model");
            }

        } catch (DbException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
    }

    byte[] cmd_cache = new byte[128];
    int wait_length = 0;
    int current_length = 0;
    byte crc = 0;

    void handle_msg_data(byte[] data) {

        Log.i(TAG, "handle_msg_data<");
        StringBuilder stringBuilder = new StringBuilder(data.length);
        for (byte byteChar : data)
            stringBuilder.append(String.format("%02X ", byteChar));

        Log.i(TAG, "handle_msg_data motor_data:" + stringBuilder.toString());
        if (data == null)
            return;

        if (data != null && wait_length == 0 && current_length == 0
                && data.length > 3) {

            switch (data[2]) {

                case 0x0f:
                case 0x1f:
                case 0x36:
                case (byte) 0xbf:
                    wait_length = data[1];
                    System.arraycopy(data, 0, cmd_cache, current_length,
                            data.length);
                    current_length += data.length;

                    if (current_length >= wait_length) {

                        do_motor_data(data);
                        wait_length = 0;
                        current_length = 0;
                        break;
                    }

                    Log.i(TAG, "current_length:" + current_length + "wait_length:"
                            + wait_length + "data[1]:" + data[1]);
                    Log.i(TAG, "handle_msg_data exit 0 >");
                    break;

                default:
                    do_motor_data(data);
                    wait_length = 0;
                    current_length = 0;
                    Log.i(TAG, "handle_msg_data exit 1 >");
                    break;
            }

            return;
        } else {
            if (current_length + data.length < wait_length) {
                System.arraycopy(data, 0, cmd_cache, current_length,
                        data.length);
                current_length += data.length;
                Log.i(TAG, "handle_msg_data exit 2 >");
                return;
            } else {
                System.arraycopy(data, 0, cmd_cache, current_length,
                        wait_length - current_length);

                byte[] motodata = new byte[wait_length];
                System.arraycopy(cmd_cache, 0, motodata, 0, wait_length);
                do_motor_data(motodata);
                wait_length = 0;
                current_length = 0;
                Log.i(TAG, "handle_msg_data exit 3>");
            }
        }

    }

    void do_motor_data(byte[] motodata) {
        StringBuilder stringBuilder = new StringBuilder(motodata.length);
        for (byte byteChar : motodata)
            stringBuilder.append(String.format("%02X ", byteChar));
        Log.d("hys123", "do_motor_data motor_data:" + stringBuilder.toString());

        sendCmdTime = 0;

        if (motodata.length >= 5 && motodata.length < 10) {
            Log.d("hys123", "do_motor_data motor_data:" + motodata);
            switch (motodata[2]) {
                case 0x18:

                case 0x38:

                    RobotStatus();

                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            count_times = 59;
                            motor_isruning = true;
                        }
                    }, 300);
                    break;

                default:
                    updateMotorCommandEcho(motodata);
                    settingdata = motodata;
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            count_times = 59;
                            motor_isruning = true;
                        }
                    }, 300);
                    break;
            }
        } else {
            handle_message_data(motodata);
            updateMotorRuning();
        }

    }

    private void handle_message_data(byte[] data) {

        if (data.length == 0) {
            return;
        }
        if (statusMessage.isMotorStatusMessage(data)) {
            motor_is_waitingstatus = false;
            statusMessage.handle_motor_message(data, tanvalue, Lrefcurrent,
                    empty_load, full_load);
        }

        if (infoMessage.isModorDeviceInfoMessage(data)) {
            infoMessage.handleMotoMessage(data);
            motor_is_waitinginfo = false;
            motor_infoBoolean = false;
        }

    }



    private void updateMotorCommandEcho(byte[] data){

        Log.d("hys123","MotorMonitorActivity updateMotorCommandEcho data == "+ data + "ParameterSetActivity == " + ParameterSetActivity.getInstance());
        if(ParameterSetActivity.getInstance() != null && ParameterSetActivity.getInstance().mMonitorSettingFragment !=null) {
            Intent mIntent = new Intent();
            mIntent.putExtra(MonitorSettingFragment.COMMAND_ECHO, data);
            ParameterSetActivity.getInstance().mMonitorSettingFragment.onActivityResult(0, MonitorSettingFragment.COMMAND_ECHO_CODE, mIntent);
        }

    }

    private MotorSingleStatusMessage statusMessage = new MotorSingleStatusMessage();
    private MotorDeviceInfoMessage infoMessage = new MotorDeviceInfoMessage();


    public MotorSingleStatusMessage getStatusMessage() {
        return statusMessage;
    }

    public MotorDeviceInfoMessage getinfoMessage() {
        return infoMessage;
    }

    private void updateMotorRuning() {
        send_message_to_groups();
        if(ParameterSetActivity.getInstance() != null && ParameterSetActivity.getInstance().mMonitorSettingFragment !=null) {
            ParameterSetActivity.getInstance().mMonitorSettingFragment.setInfoAndStatus(infoMessage, statusMessage);
        }
    }

    private String parseStatusInfo(){

        JSONObject mJsonObject = new JSONObject();
        tanvalue = infoMessage.getTanValue();
        Lrefcurrent = infoMessage.IrefCurrent();
        try {

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_XIANGWEI,
                    infoMessage.getSingleStatus());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_VERSION,
                    infoMessage.getMotorVersion());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_CHECK_REAL,
                    infoMessage.isMotorReal());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_WORKING_CURRENT,
                    infoMessage.getIrefCurrent());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_LREF_VOLT,
                    infoMessage.getLrefVolt());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_TAN_VALUE,
                    infoMessage.getTanValue());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_ENABLE_DETECT_LEAK,
                    infoMessage.isEnableDetectLeak());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_SHUTDOWN_DELAY,
                    infoMessage.getautoShutdownTime());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_SHUTGUN_DELAY,
                    infoMessage.getshutGunDelayTime());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_START_SELECTED_WAYS,
                    infoMessage.getstartUpMethod());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_PRODUCT_DATE,
                    infoMessage.getproductDateString());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_RUNED_TIME,
                    infoMessage.getmotorRunedTime());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_WORKING_FREQ,
                    infoMessage.getworkingFreq());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_START_TIMES,
                    infoMessage.getstartTimes());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_OVERLOAD_SHIELD,
                    infoMessage.isEnableOverloadShield());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_STARTGUN_DELAY,
                    infoMessage.getStartGunDelayTime());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_MAX_RUNNING_TIME,
                    infoMessage.getMaxContinueRuningTime());

            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_CURRENT,
                    statusMessage.motorSingleStatusCurrent());
            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_VOLTAGE,
                    statusMessage.motorSingleStatusVoltage());

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return  mJsonObject.toString();

    }

    private void send_message_to_all() {

        //Intent mIntent = new Intent();

        JSONObject mJsonObject = new JSONObject();
        tanvalue = infoMessage.getTanValue();
        Lrefcurrent = infoMessage.IrefCurrent();
        try {

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_XIANGWEI,
                    infoMessage.getSingleStatus());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_VERSION,
                    infoMessage.getMotorVersion());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_CHECK_REAL,
                    infoMessage.isMotorReal());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_WORKING_CURRENT,
                    infoMessage.getIrefCurrent());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_LREF_VOLT,
                    infoMessage.getLrefVolt());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_TAN_VALUE,
                    infoMessage.getTanValue());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_ENABLE_DETECT_LEAK,
                    infoMessage.isEnableDetectLeak());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_SHUTDOWN_DELAY,
                    infoMessage.getautoShutdownTime());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_SHUTGUN_DELAY,
                    infoMessage.getshutGunDelayTime());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_START_SELECTED_WAYS,
                    infoMessage.getstartUpMethod());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_PRODUCT_DATE,
                    infoMessage.getproductDateString());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_RUNED_TIME,
                    infoMessage.getmotorRunedTime());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_WORKING_FREQ,
                    infoMessage.getworkingFreq());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_START_TIMES,
                    infoMessage.getstartTimes());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_OVERLOAD_SHIELD,
                    infoMessage.isEnableOverloadShield());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_STARTGUN_DELAY,
                    infoMessage.getStartGunDelayTime());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_MAX_RUNNING_TIME,
                    infoMessage.getMaxContinueRuningTime());

            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_CURRENT,
                    statusMessage.motorSingleStatusCurrent());
            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_VOLTAGE,
                    statusMessage.motorSingleStatusVoltage());

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.i(TAG, "cmd:" + mJsonObject.toString());
        //mIntent.putExtra(MonitorInfoFragment.MOTOR_STATUS_INFO,
        //        mJsonObject.toString());
       // mMonitorInfoFragment.onActivityResult(0,
       //         MonitorRunningInfoFragment.UPDATE_STATUS_INFO, mIntent);

    }

    private void send_message_to_groups() {
        Intent mIntent = new Intent();

        JSONObject mJsonObject = new JSONObject();
        tanvalue = infoMessage.getTanValue();
        Lrefcurrent = infoMessage.IrefCurrent();
        full_load = infoMessage.getFullLoadPara();
        empty_load = infoMessage.getEmptyLoadPara();

        try {

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_RUNED_TIME,
                    infoMessage.getmotorRunedTime());
            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_CURRENT,
                    statusMessage.motorSingleStatusCurrent());
            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_SINGLE_STATUS_VOLTAGE,
                    statusMessage.motorSingleStatusVoltage());

            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_SIGNAL_LED_STATUS_CURRENT,
                    statusMessage.MotorSignalLed());

            mJsonObject.put(
                    MotorSingleStatusMessage.MOTOR_RUNING_LED_STATUS_CURRENT,
                    statusMessage.MotorRuningLed());
            mJsonObject.put(MotorSingleStatusMessage.MOTOR_IS_WORKING,
                    statusMessage.motorIsWorking());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_USED_ENERGY,
                    infoMessage.getMotorUsedEnergy());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_START_TIMES,
                    infoMessage.getstartTimes());

            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_USED_WATER_TIME,
                    infoMessage.getMotorUsedWaterGunTime());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_FULLLOAD_PARA,
                    infoMessage.getFullLoadPara());
            mJsonObject.put(MotorDeviceInfoMessage.MOTOR_EMPTYLOAD_PARA,
                    infoMessage.getEmptyLoadPara());

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Log.i(TAG, "cmd:" + mJsonObject.toString());

        mIntent.putExtra(MonitorStatusFragment.MOTOR_DEV_INFO,
                mJsonObject.toString());
        mMonitorStatusFragment.onActivityResult(0,
                MonitorStatusFragment.UPDATE_DEV_INFO, mIntent);
    }

    public void RobotShutdown() {
        if (mConnected)
        send_msg_to_motor(CMD_SHUTDOWN);
    }

    public void RobotStartUp() {
        if (mConnected)
        send_msg_to_motor(CMD_STARTUP);
    }

    public void RobotInfo() {
        if (mConnected)
        sendMsgtoRoomLock(mTxCharacteristic, CMD_BASE_INFO);
    }

    public void RobotStatus() {
        if (mConnected)
        sendMsgtoRoomLock(mTxCharacteristic, CMD_STATUS);
    }


    public int getmDeviceModel() {
        return mDeviceModel;
    }

   @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        finish();
    }



}
